package com.edu.demo.controller;
import com.edu.demo.constant.UserConstant;
import com.edu.demo.entity.*;
import com.edu.demo.mapper.TeacherMapper;
import com.edu.demo.pojo.AjaxResult;
import com.edu.demo.pojo.UserRole;
import com.edu.demo.service.IDepartmentService;
import com.edu.demo.service.IStudentService;
import com.edu.demo.service.ISysUserService;
import com.edu.demo.service.ITeacherService;
import com.edu.demo.utils.ExcelUtils;
import com.edu.demo.utils.SecurityUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 教师、学生管理
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jixuewei
 * @since 2023-01-12
 */
@RestController
@RequestMapping("/manage")
@Slf4j
public class SysUserController {

    @Autowired
    private ITeacherService teacherService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Autowired
    private TransactionDefinition transactionDefinition;

    /**
     * 批量添加学生或者教师
     * @param file
     * @param type
     * @return
     */
    @PostMapping("/add/excel")
    @PreAuthorize("@ps.hasPerm('sys:teacher:insert')")
    public AjaxResult addFromExcel(@RequestParam("file") MultipartFile file,@RequestParam("type") String type){
        TransactionStatus transaction = platformTransactionManager.getTransaction(transactionDefinition); //手动开启事务，添加成功全部成功，添加失败全部回滚
        try {
            List<Department> list = departmentService.list();
            Map<String,Integer> map = new HashMap<>();
            for (Department department : list) {
                map.put(department.getDeptName(),department.getId());
            }
            ExcelUtils.deptMap = map;


            if("student".equals(type)){
                List<Student> students = ExcelUtils.excelToStudents(file.getInputStream(),file.getOriginalFilename());
                studentService.saveBatch(students);
                List<UserRole> userRoles = students.stream().map(teacher -> {
                    return new UserRole(3, teacher.getId(), "student");
                }).collect(Collectors.toList());
                sysUserService.insertUserRole(userRoles);
            }else  if("teacher".equals(type)){
                List<Teacher> teachers = ExcelUtils.excelToTeachers(file.getInputStream(),file.getOriginalFilename());
                teacherService.saveBatch(teachers);
                List<UserRole> userRoles = teachers.stream().map(teacher -> {
                    return new UserRole(2, teacher.getId(), "teacher");
                }).collect(Collectors.toList());
                sysUserService.insertUserRole(userRoles);
            }
            platformTransactionManager.commit(transaction); //未发生异常，提交事务
        } catch (IOException e) {
            e.printStackTrace();
            platformTransactionManager.rollback(transaction); //发生异常，回滚事务
            return AjaxResult.error();
        }

        return AjaxResult.success();
    }


    /**按条件查找教师
     * @param teacher
     * @return
     */
    @PostMapping("/teacher/search")
    @PreAuthorize("@ps.hasPerm('sys:teacher:search')")
    public AjaxResult findTeacher(@RequestBody Teacher teacher,@RequestParam int index,@RequestParam int size){
        AjaxResult success = AjaxResult.success();
        List<Teacher> teachers = teacherService.findTeachers(teacher,index,size,success);
        success.put("data",teachers);

        return success;
    }
    /*** 返回教师信息列表
     * @param index
     * @param size
     * @return
     */
    @GetMapping("/teacher/list")
    @PreAuthorize("@ps.hasPerm('sys:teacher:list')")
    public AjaxResult getTeachers(@RequestParam int index,@RequestParam int size){
        AjaxResult success = AjaxResult.success();
        List<Teacher> teachers = teacherService.queryByPage(index, size,success);
        success.put("data",teachers);
        return success;
    }
    /**更新某教师信息
     * @param teacher
     * @return
     */
    @PostMapping("/teacher/update")
    @PreAuthorize("@ps.hasPerm('sys:teacher:update')")
    public AjaxResult updateTeacher(@RequestBody Teacher teacher){
        teacherService.updateTeacher(teacher);
        return AjaxResult.success();
    }

    /**重置教师密码
     * @param teacher
     * @return
     */
    @PostMapping("/teacher/reset/password")
    @PreAuthorize("@ps.hasPerm('sys:teacher:update')")
    public AjaxResult resetTeacherPassword(@RequestBody Teacher teacher){
        Teacher teacher1 = new Teacher();
        teacher1.setId(teacher.getId());
        teacher1.setPassword(passwordEncoder.encode("123456"));
        teacherService.updateTeacher(teacher1);
        return AjaxResult.success();
    }

    /**添加教师
     * @param teacher
     * @return
     */
    @PostMapping("/teacher/insert")
    @PreAuthorize("@ps.hasPerm('sys:teacher:insert')")
    public AjaxResult insert(@RequestBody Teacher teacher){
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(!UserConstant.ADMIN_TYPE.equals( loginUser.getType())){
            log.error("你的用户角色无法添加教师！");
            return AjaxResult.error("你的用户角色无法添加教师！");
        }
        teacher.setCreateBy(loginUser.getSysUser().getName());
        teacher.setCreateTime(new Date());
        teacher.setPassword(passwordEncoder.encode("123456"));
        if("男".equals(teacher.getSex()))
            teacher.setPhoto("https://img.duoziwang.com/2019/06/09221645716913.jpg");
        else teacher.setPhoto("https://img0.baidu.com/it/u=1871574132,1763266357&fm=253&fmt=auto&app=120&f=JPEG?w=700&h=700");
        teacherService.insertTeacher(teacher);
        return AjaxResult.success();
    }
    /**分页查询学生信息
     *
     * @param index
     * @param size
     * @return
     */
    @GetMapping("/student/list")
    @PreAuthorize("@ps.hasPerm('sys:student:list')")
    public AjaxResult studentList(@RequestParam int index, @RequestParam int size){
        AjaxResult success = AjaxResult.success();
        List<Student> students = studentService.studentList(index, size, success);
        success.put("data",students);
        return success;
    }
    /**
     * 修改学生信息
     * @param student
     * @return
     */
    @PostMapping("/student/update")
    @PreAuthorize("@ps.hasPerm('sys:student:update')")
    public AjaxResult updateStudent(@RequestBody Student student){
        studentService.updateStudent(student);
        return AjaxResult.success("修改成功");
    }
    @PostMapping("/student/reset/password")
    @PreAuthorize("@ps.hasPerm('sys:student:update')")
    public AjaxResult resetPasswordStudent(@RequestBody Student student){
        Student student1 = new Student();
        student1.setId(student.getId());
        student1.setPassword(passwordEncoder.encode("123456"));
        studentService.updateStudent(student1);
        return AjaxResult.success("修改成功");
    }

    /**
     * 添加学生
     * @param student
     * @return
     */
    @PostMapping("/student/insert")
    @PreAuthorize("@ps.hasPerm('sys:student:insert')")
    public AjaxResult insertStudent(@RequestBody Student student){
        student.setCreateTime(new Date());
        student.setPassword(passwordEncoder.encode("123456"));
        int i = studentService.insertStudent(student);
        return AjaxResult.success();
    }

    /**
     * 按条件查找学生
     * @param student
     * @return
     */
    @PostMapping("/student/search")
    @PreAuthorize("@ps.hasPerm('sys:student:search')")
    public AjaxResult findStudents(@RequestBody Student student,@RequestParam int index,@RequestParam int size){
        AjaxResult success = AjaxResult.success();
       List<Student>  students = studentService.findStudents(student,index,size,success);
        success.put("data",students);
        return success;
    }


    @GetMapping("/me")
    @PreAuthorize("@ps.hasPerm('sys:student:search')")
    public AjaxResult me(){
        SysUser user = SecurityUtils.getSysUser();
        if(user!=null) user.setPassword("");
        else return AjaxResult.error("没该用户");
        return AjaxResult.success(user);
    }
}
